package com.pw.study.flink.sql;

import com.pw.study.flink.entities.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

public class $02Table {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //初始化数据
        DataStreamSource<WaterSensor> data =
                env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60));
        //初始化表环境
        StreamTableEnvironment sEnv = StreamTableEnvironment.create(env);
        //关联关系
        Table table = sEnv.fromDataStream(data);
        //执行查询
       // mc1(table);
        mc2(env,sEnv,table);


    }

    private static void mc2(StreamExecutionEnvironment env, StreamTableEnvironment sEnv, Table table) {
        sEnv.toRetractStream(table, Row.class)
                .filter(t->t.f0).
        map(t-> t.f1).print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void mc1(Table table) {
        Table result = table.groupBy($("id"))
                .aggregate($("vc").sum().as("vc_sum"))
                .select($("id"), $("vc_sum"));
        result.printSchema();
        result.execute().print();
    }

}
